/*
 * Moseycode
 * Copyright (C) 2008  Tom Gibara
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 * 
 */
package com.tomgibara.mosey.coding;

import java.util.Arrays;

public class URLFormDecoder {

	private final static int[] CHAR_LOOKUP = new int[128];
	
	static {
		final char[] chars = URLFormEncoder.CHARS;
		Arrays.fill(CHAR_LOOKUP, -1);
		for (int i = 0; i < chars.length; i++) {
			CHAR_LOOKUP[chars[i]] = i;
		}
	}
	
	private final String str;
	private final int length;
	private int position = 0;
	private int buffer = 0;
	private int bitCount = 0;
	
	public URLFormDecoder(String str) {
		if (str == null) throw new IllegalArgumentException("null str");
		this.str = str;
		length = str.length();
	}

	public byte nextByte() {
		return (byte) next(8);
		
	}
	
	public short nextShort() {
		return (short) next(16);
		
	}
	
	public int nextInt() {
		int a = next(16);
		int b = next(16);
		return a << 16 | b;
		
	}
	
	// private utility methods
	
	private int next(int count) {
		while (bitCount < count) {
			if (position == length) throw new IllegalStateException("exhausted");
			char c =  str.charAt(position);
			if (c > 127) throw new RuntimeException("illegal character in string: " + c);
			int i = CHAR_LOOKUP[c];
			if (i == -1) throw new RuntimeException("illegal character in string:" + c);
			position++;
			buffer = (buffer << URLFormEncoder.WORD_SIZE) | i;
			bitCount += URLFormEncoder.WORD_SIZE;
		}
		bitCount -= count;
		int value = (buffer >>> bitCount) & ((1 << count) - 1);
		return value;
	}
	
}
